#!/bin/bash
MIRACL_DIR="$HOME/MIRACL"
SOURCE_DIR="$HOME/20242815MIRACL"

# 1. 如果 MIRACL 已安装，退出
if [ -d "$MIRACL_DIR" ] && [ -f "$MIRACL_DIR/include/miracl.h" ] && [ -f "$MIRACL_DIR/include/mirdef.h" ]; then
    echo "MIRACL 已安装，退出脚本。"
    exit 0
fi

# 2. 下载并解压 MIRACL
echo "下载 MIRACL 源码..."
cd "$HOME"
wget https://github.com/miracl/MIRACL/archive/refs/heads/master.zip -O MIRACL-master.zip
unzip -j -aa -L MIRACL-master.zip -d "$SOURCE_DIR"
rm MIRACL-master.zip

# 3. 编译 MIRACL
cd "$SOURCE_DIR"
echo "开始安装 MIRACL..."
bash linux64
if [ $? -ne 0 ]; then
    echo "MIRACL 安装失败！"
    exit 1
fi

# 4. 复制头文件和库文件
echo "配置 MIRACL 目录..."
mkdir -p "$MIRACL_DIR/include" "$MIRACL_DIR/lib"
cp "$SOURCE_DIR/miracl.h" "$MIRACL_DIR/include/"
cp "$SOURCE_DIR/miracl.a" "$MIRACL_DIR/lib/libmiracl.a"

# 5. 确保 mirdef.h 存在并复制
if [ -f "$SOURCE_DIR/mirdef.h" ]; then
    cp "$SOURCE_DIR/mirdef.h" "$MIRACL_DIR/include/"
    echo "mirdef.h 已复制到 ~/MIRACL/include/"
else
    echo "错误：mirdef.h 不存在，MIRACL 安装可能有问题！"
    exit 1
fi

# 6. 编译测试程序
TEST_FILE="/home/kyle/linux2025/3.14/test-miracl/testmiracl.c"
if [ ! -f "$TEST_FILE" ]; then
    echo "错误：测试文件不存在！"
    exit 1
fi

echo "正在编译测试程序..."
gcc "$TEST_FILE" -I"$MIRACL_DIR/include" -L"$MIRACL_DIR/lib" -lmiracl -o testmiracl
if [ $? -ne 0 ]; then
    echo "编译失败！"
    exit 1
fi

# 7. 运行测试程序
echo "运行测试程序 testmiracl..."
./testmiracl

echo "MIRACL 安装完成！"
